package cn.edu.scau.cmi.yangmupei.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.edu.scau.cmi.yangmupei.domain.Student;
import cn.edu.scau.cmi.yangmupei.util.ScauCmiHibernateSessionFactoryUtil;

public class StudentDAO {
	private static final String NAME = "name";
	private static final String TUTOR = "tutor";
	private Session session;
	

	public void save(Student transienInstance) {
		getSession();
		Transaction transaction = session.beginTransaction();
		session.save(transienInstance);
		transaction.commit();
		System.out.println("添加成功");
	}
	
	public void delete(Student persistentInstance) {
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.delete(persistentInstance);
			transaction.commit();
			System.out.println("删除成功");
		} catch (RuntimeException re) {
			System.out.println("删除失败");
			throw re;
		}
	}
	
	public Student findById( int id) {
		
		try {
			Student instance = (Student) getSession().get("cn.edu.scau.cmi.yangmupei.domain.Student", id);
			return instance;
		} catch (RuntimeException re) {
			
			throw re;
		}
	}
	  public List findByProperty(String propertyName, Object value) {
		   
		    try {
		      String queryString = "from Student as model where model." + propertyName + "= ?";
		      Query queryObject = getSession().createQuery(queryString);
		      queryObject.setParameter(0, value);
		      return queryObject.list();
		    } catch (RuntimeException re) {
		    
		      throw re;
		    }
		  }

		  public List findByName(Object name) {
		    return findByProperty(TUTOR, name);
		  }

	public void merge(Student detachedInstance) {
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.merge(detachedInstance);
			transaction.commit();
//			return result;
			System.out.println("修改成功");
		} catch (RuntimeException re) {
			throw re;
		}
	}


	private Session getSession() {
		session=ScauCmiHibernateSessionFactoryUtil.getSession();
		return session;
	}
}
